package com.bjpowernode.dao;

import com.bjpowernode.beans.NewsType;
import com.bjpowernode.exception.MyException;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class NewsTypeDaoImp implements NewsTypeDao {
    @Override
    public ArrayList<NewsType> getAll() throws SQLException {
        ArrayList<NewsType> newsTypes = new ArrayList<>();
        Connection cn = DB.getCn();
        String sql = "select id,name from news_type";
        PreparedStatement ps = cn.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            NewsType newsType = new NewsType();
            newsType.setId(rs.getInt("id"));
            newsType.setName(rs.getString("name"));
            newsTypes.add(newsType);
        }
        DB.closeCn();
        return newsTypes;
    }

    @Override
    public NewsType get(int id) throws SQLException {
        NewsType newsType = null;
        Connection cn = DB.getCn();
        String sql = "select id,name from news_type where id=?";
        PreparedStatement ps = cn.prepareStatement(sql);
        ps.setInt(1, id);
        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            newsType.setId(rs.getInt("id"));
            newsType.setName(rs.getString("name"));
        }
        DB.closeCn();
        return newsType;
    }


    //DML：返回的是影响行数
    @Override
    public void add(NewsType newsType) throws SQLException, MyException {
        //初始化影响行数
        int rows = 0;
        Connection cn = DB.getCn();
        String sql = "insert into news_type (name) values (?)";
        PreparedStatement ps = cn.prepareStatement(sql);
        ps.setString(1, newsType.getName());
        rows = ps.executeUpdate();
        if (rows <= 0) {
            throw new MyException("影响行数为0，添加失败");
        }
        DB.closeCn();
    }

    @Override
    public void edit(NewsType newsType) throws SQLException, MyException {
        //初始化影响行数
        int rows = 0;
        Connection cn = DB.getCn();
        String sql = "update news_type set name=? where id=?";
        PreparedStatement ps = cn.prepareStatement(sql);
        ps.setString(1, newsType.getName());
        ps.setInt(2, newsType.getId());
        rows = ps.executeUpdate();
        if (rows <= 0) {
            throw new MyException("影响行数为0，修改失败");
        }
        DB.closeCn();
    }

    @Override
    public void del(int id) throws SQLException, MyException {
        //初始化影响行数
        int rows = 0;
        Connection cn = DB.getCn();
        String sql = "delete from news_type where id=?";
        PreparedStatement ps = cn.prepareStatement(sql);
        ps.setInt(1, id);
        rows = ps.executeUpdate();
        if (rows <= 0) {
            throw new MyException("影响行数为0，修改失败");
        }
        DB.closeCn();
    }
}
